<template>
  <div class="file-list-viewer">
<!--    <h1>File List for ID: {{ id }}</h1>-->
    <a-table :columns="columns" :data-source="dataList" :pagination="false">
      <template slot="images" slot-scope="text, record">
        <div class="image-list">
          <div v-for="(image, index) in record.images || []" :key="index" class="image-preview">
            <img :src="imgBase + '/' + image" alt="Preview" @click="showLargeImage(imgBase + '/' + image)" />
            <a-button type="link" @click="deleteImage(record, image)" class="delete-btn">
              <a-icon type="delete" />
            </a-button>
          </div>
        </div>
      </template>
      <template slot="action" slot-scope="text, record">
        <j-upload
          :multiple="false"
          :showUploadList="false"
         @change="handleUploadChange($event,record)"
        >

        </j-upload>
      </template>
    </a-table>

    <a-modal v-model="largeImageVisible" :footer="null" @cancel="closeLargeImage">
      <img
        v-if="currentLargeImage"
        :src="currentLargeImage"
        :style="{ transform: `rotate(${rotation}deg)` }"
        class="large-image"
      />
      <div class="image-controls">
        <a-button @click="rotateImage(-90)">Rotate Left</a-button>
        <a-button @click="rotateImage(90)">Rotate Right</a-button>
      </div>
    </a-modal>
  </div>
</template>

<script>
import { deleteAction } from '../../../api/manage'
import { tableImgMixin, tableMixin } from '@views/user/register/reg_components/mixin'
export default {
  name: 'FileListViewer',
  mixins: [tableMixin, tableImgMixin],
  data() {
    return {
      id: this.$route.params.id,
      dataList: [],
      columns: [
        {
          title: 'ID',
          dataIndex: 'id',
          key: 'id',
        },
        {
          title: '名称',
          dataIndex: 'name',
          key: 'name',
        },
        {
          title: '图片',
          dataIndex: 'images',
          key: 'images',
          scopedSlots: { customRender: 'images' },
        },
        {
          title: '操作',
          key: 'action',
          scopedSlots: { customRender: 'action' },
        },
      ],
      largeImageVisible: false,
      currentLargeImage: '',
      rotation: 0,
    }
  },
  mounted() {
    this.fetchDataList()
  },
  methods: {
    async fetchDataList() {
      try {
        this.$http.get(`register/agencyLegalFile/list`, { params: { ...this.$route.query } }).then(response => {
          this.dataList = response.result.records.map(item => ({
            ...item,
            images: (item.path && item.path.split(',')) || [],
          }))
        })
        //   // 模拟API调用
        //   const response = await new Promise(resolve =>
        //     setTimeout(
        //       () =>
        //         resolve([
        //           {
        //             id: 1,
        //             name: 'Item 1',
        //             images: [
        //               { id: 1, url: '/placeholder.svg?height=100&width=100' },
        //               { id: 2, url: '/placeholder.svg?height=100&width=100' },
        //             ],
        //           },
        //           {
        //             id: 2,
        //             name: 'Item 2',
        //             images: [{ id: 3, url: '/placeholder.svg?height=100&width=100' }],
        //           },
        //           {
        //             id: 3,
        //             name: 'Item 3',
        //             images: [],
        //           },
        //         ]),
        //       1000,
        //     ),
        //   )

        //   this.dataList = response.map(item => ({
        //     ...item,
        //     images: item.images || [],
        //   }))
      } catch (error) {
        console.error('Error fetching data:', error)
        this.$message.error('Failed to fetch data list')
      }
    },
    deleteImage(record, url) {
      let path = record.path
      if(record.path && record.path.includes(url)){
       path = record.path.split(',').filter(item=>item!==url).join()
      }
      this.$http.post('/register/agencyLegalFile/edit',{...record,path}).then(r=>{
        this.fetchDataList()
      })
      // const dataItem = this.dataList.find(item => item.id === dataId)
      // if (dataItem && dataItem.images) {
      //   dataItem.images = dataItem.images.filter(img => img.id !== imageId)
      //   this.$message.success('Image deleted successfully')
      // }
    },
    showLargeImage(image) {
      if (image) {
        this.currentLargeImage = image
        this.largeImageVisible = true
        this.rotation = 0
      }
    },
    closeLargeImage() {
      this.largeImageVisible = false
      this.currentLargeImage = ''
      this.rotation = 0
    },
    rotateImage(degree) {
      this.rotation += degree
    },
    customUpload({ file, onSuccess, onError }, dataId) {
      // 模拟文件上传
      setTimeout(() => {
        try {
          const newImage = {
            id: Date.now(),
            url: URL.createObjectURL(file),
          }
          const dataItem = this.dataList.find(item => item.id === dataId)
          if (dataItem) {
            if (!dataItem.images) {
              dataItem.images = []
            }
            dataItem.images.push(newImage)
            onSuccess(newImage, file)
          } else {
            throw new Error('Data item not found')
          }
        } catch (error) {
          console.error('Error uploading file:', error)
          onError(error)
        }
      }, 1000)
    },
    handleUploadChange(info, record) {
      console.log(info)
      console.log(record)
      if(!info)return;
      if(info){
        let fileList = info.split(',')
        let lastfile = fileList[fileList.length-1]
        let path = lastfile
        if(record.path){
          path = record.path + ',' + lastfile
        }
        this.$http.post('/register/agencyLegalFile/edit',{...record,path,}).then(r=>{
          console.log(r)
          this.fetchDataList()
        })
      }
     /* if (info.file.status === 'done') {
        this.$message.success(`${info.file.name} file uploaded successfully to item ${dataId}`)
        this.fetchDataList()
      } else if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} file upload failed.`)
      }*/
    },
  },
}
</script>

<style scoped>
.file-list-viewer {
  padding: 24px;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.image-preview {
  position: relative;
  display: inline-block;
}

.image-preview img {
  width: 100px;
  height: 100px;
  object-fit: cover;
  cursor: pointer;
}

.delete-btn {
  position: absolute;
  top: 0;
  right: 0;
  background: rgba(0,0,0, 0.3);
}

.large-image {
  max-width: 100%;
  max-height: 70vh;
}

.image-controls {
  margin-top: 16px;
  text-align: center;
}
</style>
